package cn.itsource.basic.config.interceptor;


import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PetConstant;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.pojo.info.LoginInfo;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component //交给spring管理
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("请求地址,{}",request.getRequestURL());

        //1.从req获取token
        String token = request.getHeader("token");

        //1.1判断token如果为null,返回false
        if (StringUtils.isBlank(token)) {
            //标识响应的是json格式 springmvc第二天学的
            //返回登录失效信息.code = 1001
            return loginTimeOut(response);
        }

        //2.token做为key,从redis获取用户信息
        LoginInfo loginInfo = redisService.getKeyObjectValue(token, LoginInfo.class);

        //2.1如果获取失败,返回false
        if (loginInfo == null) {
            //返回登录失效信息.code = 1001
            return loginTimeOut(response);
        }

        //3.重置redis的30分钟倒计时
        redisService.setStringKeyAndValue(token,loginInfo,30);
        //4.放行
        return true;
    }

    /**
     * 自动抽取 alt + shift + m
     * @param response
     * @return
     * @throws IOException
     */
    private boolean loginTimeOut(HttpServletResponse response) throws IOException {
        //标识响应的是json格式 springmvc第二天学的
        response.setContentType("application/json;charset=utf-8");

        //1.2返回一个状态码,标识登录无效了
        PrintWriter writer = response.getWriter();
        AjaxResult ajaxResult = AjaxResult.createError(PetConstant.SYSTEM_LOGIN_TIMEOUT, "请重新登录");

        writer.write(JSONObject.toJSONString(ajaxResult));
        return false;
    }
}
